package service.impl;

import common.Constants;
import domain.Comment;
import exceptions.GeneralServiceException;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import service.ICommentService;

/**
 *
 * @author yuyok
 */
@Stateless
@LocalBean
public class CommentServiceImpl extends GenericServiceImpl<Comment> implements ICommentService {

    @PersistenceContext(unitName = "onlinetvPU")
    private EntityManager em;

    public CommentServiceImpl() {
        super(Comment.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
  
    // TODO: rewrite using JPQL
    @Override
    public boolean validateComment(Comment comment, Long videoId, Long userId) throws IllegalArgumentException {

        if (comment == null || videoId == null || userId == null) {
            throw new IllegalArgumentException("Comment cannot be null while getting User by these fields");
        }

        String query = "SELECT user_id "
                + "FROM Comment "
                + "WHERE video_id = ? "
                + "ORDER BY addedDate desc "
                + "LIMIT " + Constants.ALLOWED_COMMENTS_COUNT.toString();

        Query q = getEntityManager().createNativeQuery(query);
        q.setParameter(1, videoId);

        List<BigInteger> ids = q.getResultList();

        if (ids.size() == Constants.ALLOWED_COMMENTS_COUNT) {
            HashSet set = new HashSet();
            for (int i = 0; i < ids.size(); i++) {
                set.add(ids.get(i));
            }
            if (set.size() == 1) {
                BigInteger firstEl = (BigInteger) set.iterator().next();
                if (firstEl.longValue() == userId)
                    return false; 
            }
        }

        try {
            save(comment);
        } catch (GeneralServiceException ex) {
            Logger.getLogger(CommentServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    }

    @Override
    public List<Comment> getAllComments() {
        Query query = getEntityManager().createNamedQuery("getAllComments");
        
        return query.getResultList();
    }
    
}
